home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Cream of the Crop 26
/
Cream of the Crop 26.iso
/
program
/
ccdl150l.zip
/
ALLOC
/
MALLOC.C
< prev
next >
Wrap
C/C++ Source or Header
|
1997-06-12
|
2KB
|
87 lines
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <libp.h>
void *_allocbloc = 0;
int _allocflag = 0;
#pragma rundown memdelete 1
void memdelete(void)
{
BLKHEAD *p = _allocbloc;
while (p) {
BLKHEAD *n = p->next;
_ll_free(p);
p = n;
}
}
static int init_block(BLKHEAD **blk, size_t size)
{
size_t ns = size+sizeof(size_t)+sizeof(BLKHEAD)+sizeof(FREELIST);
void *nb;
FREELIST *lp;
if (size < ALLOCSIZE)
ns = ALLOCSIZE;
nb = _ll_malloc(ns);
if (!nb)
return 0;
(*blk) = nb;
((BLKHEAD *)nb)->next = 0;
((BLKHEAD *)nb)->list = lp = (((char *)nb)+sizeof(BLKHEAD));
lp->next = 0;
lp->size = ns - sizeof(BLKHEAD);
return 1;
}
static void *split(FREELIST **flist, size_t size)
{
void *p = *flist;
FREELIST *flist2;
if (size < (*flist)->size - sizeof(FREELIST)-sizeof(size_t)) {
flist2 = (char *)*flist+size+sizeof(size_t);
flist2->size = ((FREELIST *)p)->size - size-sizeof(size_t);
flist2->next = (*flist)->next;
*(long *)p = size;
*flist = flist2;
}
else {
*(long *)p = size;
(*flist) = (*flist)->next;
}
return (size_t *)p+1;
}
void *malloc(size_t size)
{
BLKHEAD **blist;
FREELIST **flist;
void *p;
while (_allocflag)
_ll_transfer();
size +=3;
size &= 0xfffffffc;
_allocflag = 1;
blist = &_allocbloc;
while (*blist) {
flist = &(*blist)->list;
while (*flist) {
if ((*flist)->size > size+sizeof(size_t)) {
p =split(flist,size);
_allocflag = 0;
return p;
}
flist = &((*flist)->next);
}
blist = &(*blist)->next;
}
if (!init_block(blist,size)) {
_allocflag = 0;
return 0;
}
flist = &(*blist)->list;
p = split(flist,size);
_allocflag = 0;
return p;
}